<template>
  <div class="profile-container">
    <!-- 导航栏 -->
    <Navbar />
    
    <div class="container">
      <div class="profile-content">
        <!-- 统计数据卡片 -->
        <div class="stats-section">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><ShoppingCart /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ userStats.totalOrders }}</div>
              <div class="stat-label">总订单数</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><Van /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ userStats.pendingShipment }}</div>
              <div class="stat-label">代发货</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><CreditCard /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">¥{{ userStats.totalSpent.toFixed(2) }}</div>
              <div class="stat-label">累计消费</div>
            </div>
          </div>
        </div>

        <!-- 个人信息 -->
        <div class="profile-card">
          <div class="card-header">
            <div class="header-left">
              <el-icon><User /></el-icon>
              <h3>个人信息</h3>
            </div>
            <button 
              @click="toggleEdit" 
              class="btn btn-secondary"
              :disabled="loading"
            >
              <el-icon>
                <component :is="isEditing ? 'Close' : 'Edit'" />
              </el-icon>
              {{ isEditing ? '取消' : '编辑' }}
            </button>
          </div>
          <div class="card-content">
            <form @submit.prevent="saveProfile" class="profile-form">
              <div class="form-grid">
                <div class="form-group">
                  <label for="username">用户名</label>
                  <input
                    id="username"
                    v-model="userForm.username"
                    type="text"
                    class="form-input"
                    :disabled="!isEditing"
                    placeholder="请输入用户名"
                  >
                </div>
                <div class="form-group">
                  <label for="email">邮箱</label>
                  <input
                    id="email"
                    v-model="userForm.email"
                    type="email"
                    class="form-input"
                    :disabled="!isEditing"
                    placeholder="请输入邮箱"
                  >
                </div>
                <div class="form-group">
                  <label for="phone">手机号</label>
                  <input
                    id="phone"
                    v-model="userForm.phone"
                    type="tel"
                    class="form-input"
                    :disabled="!isEditing"
                    placeholder="请输入手机号"
                  >
                </div>
                <div class="form-group">
                  <label for="realName">真实姓名</label>
                  <input
                    id="realName"
                    v-model="userForm.realName"
                    type="text"
                    class="form-input"
                    :disabled="!isEditing"
                    placeholder="请输入真实姓名"
                  >
                </div>
              </div>
              <div v-if="isEditing" class="form-actions">
                <button 
                  type="submit" 
                  class="btn btn-primary"
                  :disabled="loading"
                >
                  <el-icon><Check /></el-icon>
                  {{ loading ? '保存中...' : '保存' }}
                </button>
                <button 
                  type="button" 
                  @click="resetForm" 
                  class="btn btn-secondary"
                  :disabled="loading"
                >
                  <el-icon><RefreshLeft /></el-icon>
                  重置
                </button>
              </div>
            </form>
          </div>
        </div>

        <!-- 快捷操作 -->
        <div class="quick-actions">
          <h3>
            <el-icon><Lightning /></el-icon>
            快捷操作
          </h3>
          <div class="actions-grid">
            <div class="action-card" @click="$router.push('/orders')">
              <div class="action-icon">
                <el-icon><List /></el-icon>
              </div>
              <div class="action-info">
                <h4>我的订单</h4>
                <p>查看所有订单记录</p>
              </div>
            </div>
            <div class="action-card" @click="$router.push('/cart')">
              <div class="action-icon">
                <el-icon><ShoppingCart /></el-icon>
              </div>
              <div class="action-info">
                <h4>购物车</h4>
                <p>管理购物车商品</p>
              </div>
            </div>
            <div class="action-card" @click="contactService">
              <div class="action-icon">
                <el-icon><Service /></el-icon>
              </div>
              <div class="action-info">
                <h4>联系客服</h4>
                <p>获取帮助和支持</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 浮动购物车 -->
    <FloatingCart />
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage, ElNotification } from 'element-plus'
import Navbar from '@/components/Navbar.vue'
import FloatingCart from '@/components/FloatingCart.vue'
import { userAPI, orderAPI } from '@/api'
import { getCurrentUser, isUserLoggedIn } from '@/utils/auth'
import { 
  User, 
  ShoppingCart, 
  Van, 
  CreditCard, 
  Edit, 
  Close, 
  Check, 
  RefreshLeft, 
  Lightning, 
  List, 
  Service 
} from '@element-plus/icons-vue'

export default {
  name: 'UserProfileView',
  components: {
    Navbar,
    FloatingCart,
    User,
    ShoppingCart,
    Van,
    CreditCard,
    Edit,
    Close,
    Check,
    RefreshLeft,
    Lightning,
    List,
    Service
  },
  setup() {
    const router = useRouter()
    const store = useStore()
    
    const loading = ref(false)
    const isEditing = ref(false)
    
    const userForm = reactive({
      username: '',
      email: '',
      phone: '',
      realName: ''
    })

    const userStats = reactive({
      totalOrders: 0,
      pendingShipment: 0,
      totalSpent: 0
    })

    const originalUserData = ref({})

    const loadUserProfile = async () => {
      try {
        loading.value = true
        
        // 检查用户登录状态
        if (!isUserLoggedIn()) {
          ElMessage.warning('请先登录')
          router.push('/login')
          return
        }
        
        let currentUser = getCurrentUser()
        
        // 同步到store
        if (currentUser) {
          store.commit('setUser', currentUser)
        }
        
        // 从API重新获取最新的用户信息
        try {
          const response = await userAPI.getUserInfo(currentUser.userId)
          if (response.success && response.user) {
            currentUser = response.user
            store.commit('setUser', currentUser)
          }
        } catch (error) {
          console.warn('获取最新用户信息失败，使用缓存数据:', error)
        }
        
        // 设置表单数据
        userForm.username = currentUser.username || ''
        userForm.email = currentUser.email || ''
        userForm.phone = currentUser.phoneNumber || currentUser.phone || ''
        userForm.realName = currentUser.realName || ''
        
        // 保存原始数据
        originalUserData.value = { ...userForm }
        
        // 获取用户统计数据
        await loadUserStats(currentUser.userId)
        
      } catch (error) {
        console.error('获取用户信息失败:', error)
        ElMessage.error('获取用户信息失败，请重新登录')
        router.push('/login')
      } finally {
        loading.value = false
      }
    }

    const loadUserStats = async (userId) => {
      try {
        // 获取用户订单统计
        const ordersResponse = await orderAPI.getUserOrders(userId)
        const orders = ordersResponse.orders || ordersResponse || []
        
        userStats.totalOrders = orders.length
        userStats.pendingShipment = orders.filter(order => 
          order.orderStatus === 'PAID' || order.orderStatus === 'paid'
        ).length
        userStats.totalSpent = orders.reduce((total, order) => {
          return total + (parseFloat(order.totalAmount) || 0)
        }, 0)
      } catch (error) {
        console.error('获取用户统计失败:', error)
        // 设置默认值
        userStats.totalOrders = 0
        userStats.pendingShipment = 0
        userStats.totalSpent = 0
      }
    }

    const toggleEdit = () => {
      if (isEditing.value) {
        // 取消编辑，恢复原始数据
        Object.assign(userForm, originalUserData.value)
      }
      isEditing.value = !isEditing.value
    }

    const resetForm = () => {
      Object.assign(userForm, originalUserData.value)
    }

    const saveProfile = async () => {
      try {
        loading.value = true
        const currentUser = store.getters.currentUser
        
        const updateData = {
          userId: currentUser.userId,
          username: userForm.username,
          email: userForm.email,
          phoneNumber: userForm.phone, // 注意这里使用phoneNumber
          realName: userForm.realName
        }

        await userAPI.updateUser(updateData)
        
        // 更新store中的用户信息
        store.commit('updateUser', updateData)
        
        // 更新原始数据
        originalUserData.value = { ...userForm }
        
        isEditing.value = false
        ElMessage.success('个人信息更新成功！')
      } catch (error) {
        console.error('更新个人信息失败:', error)
        ElMessage.error('更新失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }

    const contactService = () => {
      ElNotification({
        title: '客服信息',
        message: '客服电话：400-888-8888\n工作时间：9:00-18:00',
        type: 'info',
        duration: 0
      })
    }

    onMounted(() => {
      loadUserProfile()
    })

    return {
      loading,
      isEditing,
      userForm,
      userStats,
      toggleEdit,
      resetForm,
      saveProfile,
      contactService
    }
  }
}
</script>

<style scoped>
.profile-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
  color: #ffffff;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.profile-content {
  display: flex;
  flex-direction: column;
  gap: 32px;
}

.profile-card {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 16px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.profile-card:hover {
  background: rgba(255, 255, 255, 0.15);
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  background: rgba(255, 255, 255, 0.05);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-left i {
  font-size: 24px;
  color: #00D4FF;
}

.header-left h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #ffffff;
}

.card-content {
  padding: 24px;
}

.profile-form {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-size: 14px;
  font-weight: 500;
  color: #B0BEC5;
}

.form-input {
  padding: 12px 16px;
  border: 2px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.1);
  color: #ffffff;
}

.form-input::placeholder {
  color: rgba(176, 190, 197, 0.7);
}

.form-input:focus {
  outline: none;
  border-color: #00D4FF;
  box-shadow: 0 0 0 3px rgba(0, 212, 255, 0.2);
  background: rgba(255, 255, 255, 0.15);
}

.form-input:disabled {
  background: rgba(255, 255, 255, 0.05);
  color: #B0BEC5;
  cursor: not-allowed;
  border-color: rgba(255, 255, 255, 0.1);
}

.form-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-start;
}

.btn {
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  text-decoration: none;
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-primary {
  background: linear-gradient(45deg, #00D4FF, #4F46E5);
  color: white;
  border: 1px solid transparent;
}

.btn-primary:hover:not(:disabled) {
  background: linear-gradient(45deg, #00B8E6, #3F3BE0);
  transform: translateY(-1px);
  box-shadow: 0 4px 15px rgba(0, 212, 255, 0.3);
}

.btn-secondary {
  background: rgba(255, 255, 255, 0.1);
  color: #B0BEC5;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.btn-secondary:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.2);
  color: #ffffff;
}

.stats-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.stat-card {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  padding: 24px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  gap: 16px;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-4px);
  background: rgba(0, 212, 255, 0.2);
  box-shadow: 0 8px 30px rgba(0, 212, 255, 0.3);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
  background: linear-gradient(135deg, #00D4FF, #4F46E5);
}

.stat-card:nth-child(2) .stat-icon {
  background: linear-gradient(135deg, #00D4FF, #00B8E6);
}

.stat-card:nth-child(3) .stat-icon {
  background: linear-gradient(135deg, #4F46E5, #7C3AED);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 32px;
  font-weight: 700;
  color: #00D4FF;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #B0BEC5;
  font-weight: 500;
}

.quick-actions {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  padding: 24px;
  border-radius: 16px;
}

.quick-actions h3 {
  margin: 0 0 24px 0;
  font-size: 20px;
  font-weight: 600;
  color: #ffffff;
  display: flex;
  align-items: center;
  gap: 12px;
}

.quick-actions h3 i {
  color: #00D4FF;
}

.actions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.action-card {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.05);
  border: 2px solid rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-card:hover {
  border-color: #00D4FF;
  background: rgba(0, 212, 255, 0.1);
  transform: translateY(-2px);
}

.action-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
  background: linear-gradient(135deg, #00D4FF, #4F46E5);
}

.action-card:nth-child(2) .action-icon {
  background: linear-gradient(135deg, #00D4FF, #00B8E6);
}

.action-card:nth-child(3) .action-icon {
  background: linear-gradient(135deg, #4F46E5, #7C3AED);
}

.action-info h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #ffffff;
}

.action-info p {
  margin: 0;
  font-size: 14px;
  color: #B0BEC5;
}

@media (max-width: 768px) {
  .container {
    padding: 12px;
  }
  
  .form-grid {
    grid-template-columns: 1fr;
  }
  
  .stats-section {
    grid-template-columns: 1fr;
  }
  
  .actions-grid {
    grid-template-columns: 1fr;
  }
  
  .form-actions {
    flex-direction: column;
  }
}
</style> 